package main

import (
	"fmt"
	"math/rand"
	"time"
)

func generator() chan int {
	out := make(chan int)
	go func() {
		i := 0
		for {
			time.Sleep(time.Duration(rand.Intn(1500)) * time.Millisecond)
			out <- i
			i++
		}
	}()
	return out
}

func worker(id int, c chan int) {
	for n := range c {
		time.Sleep(1 * time.Second)
		fmt.Printf("Worker %d received %d\n", id, n)
	}
}

func createWorker(id int) chan<- int {
	c := make(chan int)
	go worker(id, c)
	return c
}

func main() {
	// 生成数据和消耗数据的速度不一样，后产生的数据会冲掉之前的数据，会跳跃打印
	// 数据需要排队
	var c1, c2 = generator(), generator()
	var worker = createWorker(0)
	n := 0
	var values []int                   // 数据缓冲消费数据太慢
	tm := time.After(10 * time.Second) // 返回一个channel，10秒后往channel送一个时间
	tick := time.Tick(time.Second)     //定时
	for {
		var activeWorker chan<- int // nil channel
		var activeValues int
		if len(values) > 0 {
			activeWorker = worker
			activeValues = values[0]
		}
		select {
		// 同时从c1和c2中拿数据，谁快从谁那里拿
		case n = <-c1:
			values = append(values, n)
		case n = <-c2:
			values = append(values, n)

		case activeWorker <- activeValues:
			values = values[1:]
		case <-time.After(800 * time.Millisecond): //超过800ms打印timeout
			fmt.Println("timeout")
		case <-tick:
			fmt.Println("queue len =", len(values)) // 定时打印缓冲区时长
		case <-tm: // 计时器，终止函数
			fmt.Println("bye")
			return

		}
	}
}
